---
title: Social Authentication
sidebar_label: Social Auth
---

Social authentication is a multi-step authentication flow, allowing you to sign a user into an account or link
them with an existing one.

Both native platforms and web support creating a credential which can then be passed to the [`signInWithCredential`](!firebase_auth.FirebaseAuth.signInWithCredential)
or [`linkWithCredential`](!firebase_auth.User.linkWithCredential) methods. Alternatively on web platforms, you can trigger the authentication process via
a popup or redirect.

## Google

Most configuration is already setup when using Google Sign-In with Firebase, however you need to ensure your machine's
SHA1 key has been configured for use with Android. You can see how to generate the key on the
[Installation](../installation/android#generating-firebase-credentials) documentation.

Ensure the "Google" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).

> If your user signs in with Google, after having already manually registered an account, their authentication provider will automatically
> change to Google, due to Firebase Authentications concept of trusted providers. You can find out more about
> this [here](https://groups.google.com/g/firebase-talk/c/ms_NVQem_Cw/m/8g7BFk1IAAAJ).

<Tabs
  defaultValue="native"
  values={[
    { label: 'Native', value: 'native', },
    { label: 'Web', value: 'web', },
  ]
}>
<TabItem value="native">

On native platforms, a 3rd party library is required to trigger the authentication flow.

Install the official [`google_sign_in`](https://pub.dev/packages/google_sign_in) plugin:

```yaml title="pubspec.yaml"
dependencies:
  google_sign_in: "{{ external.google_sign_in }}"
```

Once installed, trigger the sign-in flow and create a new credential:

```dart
import 'package:google_sign_in/google_sign_in.dart';

Future<UserCredential> signInWithGoogle() async {
  // Trigger the authentication flow
  final GoogleSignInAccount googleUser = await GoogleSignIn().signIn();

  // Obtain the auth details from the request
  final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

  // Create a new credential
  final GoogleAuthCredential credential = GoogleAuthProvider.credential(
    accessToken: googleAuth.accessToken,
    idToken: googleAuth.idToken,
  );

  // Once signed in, return the UserCredential
  return await FirebaseAuth.instance.signInWithCredential(credential);
}
```

</TabItem>
<TabItem value="web">

On the web, the Firebase SDK provides support for automatically handling the authentication flow using your Firebase project. For example:

Create a Google auth provider, providing any additional [permission scope](https://developers.google.com/identity/protocols/oauth2/scopes)
you wish to obtain from the user:

```dart
GoogleAuthProvider googleProvider = GoogleAuthProvider();

googleProvider.addScope('https://www.googleapis.com/auth/contacts.readonly');
googleProvider.setCustomParameters({
  'login_hint': 'user@example.com'
});
```

Provide the credential to the [`signInWithPopup`](!firebase_auth.FirebaseAuth.signInWithPopup) method. This will trigger a new
window to appear prompting the user to sign-in to your project. Alternatively you can use `signInWithRedirect` to keep the
authentication process in the same window.

```dart
Future<UserCredential> signInWithGoogle() async {
  // Create a new provider
  GoogleAuthProvider googleProvider = GoogleAuthProvider();

  googleProvider.addScope('https://www.googleapis.com/auth/contacts.readonly');
  googleProvider.setCustomParameters({
    'login_hint': 'user@example.com'
  });

  // Once signed in, return the UserCredential
  return await FirebaseAuth.instance.signInWithPopup(googleProvider);

  // Or use signInWithRedirect
  // return await FirebaseAuth.instance.signInWithRedirect(googleProvider);
}
```

</TabItem>
</Tabs>

## Facebook

Before getting started setup your [Facebook Developer App](https://developers.facebook.com/apps/) and follow the setup process to enable Facebook Login.

Ensure the "Facebook" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers).
with the Facebook App ID and Secret set.

<Tabs
  defaultValue="native"
  values={[
    { label: 'Native', value: 'native', },
    { label: 'Web', value: 'web', },
  ]
}>
<TabItem value="native">

On native platforms, a 3rd party library is required to both install the Facebook SDK and trigger the authentication flow.

Install the [`flutter_facebook_auth`](https://pub.dev/packages/flutter_facebook_auth) plugin:

```yaml title="pubspec.yaml"
dependencies:
  flutter_facebook_auth: "{{ external.flutter_facebook_auth }}"
```

You will need to follow the steps in the plugin documentation to ensure that both the Android & iOS Facebook SDKs have been initialized
correctly. Once complete, trigger the sign-in flow, create a Facebook credential and sign the user in:

```dart
import 'package:flutter_facebook_auth/flutter_facebook_auth.dart';

Future<UserCredential> signInWithFacebook() async {
  // Trigger the sign-in flow
  final LoginResult result = await FacebookAuth.instance.login();

  // Create a credential from the access token
  final FacebookAuthCredential facebookAuthCredential =
    FacebookAuthProvider.credential(result.accessToken.token);

  // Once signed in, return the UserCredential
  return await FirebaseAuth.instance.signInWithCredential(facebookAuthCredential);
}
```

</TabItem>
<TabItem value="web">

On the web, the Firebase SDK provides support for automatically handling the authentication flow using the
Facebook application details provided on the Firebase console. For example:

Create a Facebook provider, providing any additional [permission scope](https://developers.facebook.com/docs/facebook-login/permissions/)
you wish to obtain from the user.

Ensure that the OAuth redirect URI from the Firebase console is added as a valid OAuth Redirect URI
in your Facebook App.

```dart
FacebookAuthProvider facebookProvider = FacebookAuthProvider();

facebookProvider.addScope('email');
facebookProvider.setCustomParameters({
  'display': 'popup',
});
```

Provide the credential to the [`signInWithPopup`](!firebase_auth.FirebaseAuth.signInWithPopup) method. This will trigger a new
window to appear prompting the user to sign-in to your Facebook application:

```dart
Future<UserCredential> signInWithFacebook() async {
  // Create a new provider
  FacebookAuthProvider facebookProvider = FacebookAuthProvider();

  facebookProvider.addScope('email');
  facebookProvider.setCustomParameters({
    'display': 'popup',
  });

  // Once signed in, return the UserCredential
  return await FirebaseAuth.instance.signInWithPopup(facebookProvider);

  // Or use signInWithRedirect
  // return await FirebaseAuth.instance.signInWithRedirect(facebookProvider);
}
```

</TabItem>
</Tabs>

## Apple

Apple [announced](https://developer.apple.com/news/?id=09122019b) that any applications using 3rd party login
services (such as Facebook, Twitter, Google etc) must also have an Apple Sign-In method. Apple Sign-In is not required for Android devices.

To integrate Apple Sign-In on your iOS application, you will need to install a 3rd party library to authenticate with Apple.
Once authentication is successful, a Firebase credential can then be used to sign the user into Firebase with their Apple account

The example below is based on [sign_in_with_apple](https://pub.dev/packages/sign_in_with_apple) Flutter package.

```dart
import 'dart:math';
import 'dart:convert';
import 'dart:io';
import 'package:crypto/crypto.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:firebase_auth/firebase_auth.dart';

String _createNonce(int length) {
  final random = Random();
  final charCodes = List<int>.generate(length, (_) {
    int codeUnit;

    switch (random.nextInt(3)) {
      case 0:
        codeUnit = random.nextInt(10) + 48;
        break;
      case 1:
        codeUnit = random.nextInt(26) + 65;
        break;
      case 2:
        codeUnit = random.nextInt(26) + 97;
        break;
    }

    return codeUnit;
  });

  return String.fromCharCodes(charCodes);
}

Future<OAuthCredential> _createAppleOAuthCred() async {
  final nonce = _createNonce(32);
  final nativeAppleCred = Platform.isIOS
      ? await SignInWithApple.getAppleIDCredential(
          scopes: [
            AppleIDAuthorizationScopes.email,
            AppleIDAuthorizationScopes.fullName,
          ],
          nonce: sha256.convert(utf8.encode(nonce)).toString(),
        )
      : await SignInWithApple.getAppleIDCredential(
          scopes: [
            AppleIDAuthorizationScopes.email,
            AppleIDAuthorizationScopes.fullName,
          ],
          webAuthenticationOptions: WebAuthenticationOptions(
            redirectUri: Uri.parse(
                'https://your-project-name.firebaseapp.com/__/auth/handler'),
            clientId: 'your.app.bundle.name',
          ),
          nonce: sha256.convert(utf8.encode(nonce)).toString(),
        );

  return new OAuthCredential(
    providerId: "apple.com", // MUST be "apple.com"
    signInMethod: "oauth",   // MUST be "oauth"
    accessToken: nativeAppleCred.identityToken, // propagate Apple ID token to BOTH accessToken and idToken parameters
    idToken: nativeAppleCred.identityToken,
    rawNonce: nonce,
  );
}

// sign in with Apple OAuth2 credential:

final oauthCred = await _createAppleOAuthCred();
await FirebaseAuth.instance.signInWithCredential(oauthCred);

// or link Apple OAuth2 credential to existing account:

final oauthCred = await _createAppleOAuthCred();
await FirebaseAuth.instance.currentUser.linkWithCredential(oauthCred);

```


## Twitter

Ensure the "Twitter" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers)
with an API Key and API Secret set.

<Tabs
  defaultValue="native"
  values={[
    { label: 'Native', value: 'native', },
    { label: 'Web', value: 'web', },
  ]
}>
<TabItem value="native">

On native platforms, a 3rd party library is required to both install the Twitter SDK and trigger the authentication flow.

Install the [`flutter_twitter_login`](https://pub.dev/packages/flutter_twitter_login) plugin:

```yaml title="pubspec.yaml"
dependencies:
  flutter_twitter_login: ^1.1.0
```

You will need to ensure that your application in the [Twitter Developer Portal](https://developer.twitter.com/) has
a callback URL of `twittersdk://` for Android, and `twitterkit-CONSUMERKEY://` for iOS. Once complete, trigger the sign-in flow, create a Twitter credential and sign the user in:

```dart
import 'package:flutter_twitter_login/flutter_twitter_login.dart';

Future<UserCredential> signInWithTwitter() async {
  // Create a TwitterLogin instance
  final TwitterLogin twitterLogin = new TwitterLogin(
    consumerKey: '<your consumer key>',
    consumerSecret:' <your consumer secret>',
  );

  // Trigger the sign-in flow
  final TwitterLoginResult loginResult = await twitterLogin.authorize();

  // Get the Logged In session
  final TwitterSession twitterSession = loginResult.session;

  // Create a credential from the access token
  final AuthCredential twitterAuthCredential =
    TwitterAuthProvider.credential(accessToken: twitterSession.token, secret: twitterSession.secret);

  // Once signed in, return the UserCredential
  return await FirebaseAuth.instance.signInWithCredential(twitterAuthCredential);
}
```

Please note there is an [outstanding issue](https://github.com/roughike/flutter_twitter_login/issues/32) with this package, regarding iOS and the use of `UIWebView` which is deprecated.

</TabItem>
<TabItem value="web">

On the web, the Twitter SDK provides support for automatically handling the authentication flow using the
Twitter application details provided on the Firebase console.  Ensure that the callback URL in the Firebase console is added
as a callback URL in your Twitter application on their developer console.

For example:

Create a Twitter provider and provide the credential to the [`signInWithPopup`](!firebase_auth.FirebaseAuth.signInWithPopup) method. This will trigger a new
window to appear prompting the user to sign-in to your Twitter application:

```dart
Future<UserCredential> signInWithTwitter() async {
  // Create a new provider
  TwitterAuthProvider twitterProvider = TwitterAuthProvider();


  // Once signed in, return the UserCredential
  return await FirebaseAuth.instance.signInWithPopup(twitterProvider);

  // Or use signInWithRedirect
  // return await FirebaseAuth.instance.signInWithRedirect(twitterProvider);
}
```

</TabItem>
</Tabs>

## GitHub

Ensure that you have setup an OAuth App from your [GitHub Developer Settings](https://github.com/settings/developers) and
that the "GitHub" sign-in provider is enabled on the [Firebase Console](https://console.firebase.google.com/project/_/authentication/providers)
with the Client ID and Secret are set, with the callback URL set in the GitHub app.


<Tabs
  defaultValue="native"
  values={[
    { label: 'Native', value: 'native', },
    { label: 'Web', value: 'web', },
  ]
}>
<TabItem value="native">

On native platforms, a 3rd party library is required to both install the GitHub SDK and trigger the authentication flow.

Install the [`github_sign_in`](https://pub.dev/packages/github_sign_in) plugin:

```yaml title="pubspec.yaml"
dependencies:
  github_sign_in: ^0.0.1
```

You will need to populate the `GitHubSignIn` instance with your GitHub Client ID, GitHub Client Secret and also a Redirect URL (Firebase callback url).
Once complete trigger the sign-in flow, create a GitHub credential and sign the user in:

```dart
import 'package:github_sign_in/github_sign_in.dart';

Future<UserCredential> signInWithGitHub() async {
  // Create a GitHubSignIn instance
      final GitHubSignIn gitHubSignIn = GitHubSignIn(
          clientId: clientId,
          clientSecret: clientSecret,
          redirectUrl: 'https://my-project.firebaseapp.com/__/auth/handler');

  // Trigger the sign-in flow
  final result = await gitHubSignIn.signIn(context);

  // Create a credential from the access token
  final AuthCredential githubAuthCredential = GithubAuthProvider.credential(result.token);

  // Once signed in, return the UserCredential
  return await FirebaseAuth.instance.signInWithCredential(githubAuthCredential);
}
```

</TabItem>
<TabItem value="web">

On the web, the GitHub SDK provides support for automatically handling the authentication flow using the
GitHub application details provided on the Firebase console.  Ensure that the callback URL in the Firebase console is added
as a callback URL in your GitHub application on the developer console.

For example:

Create a GitHub provider and provide the credential to the [`signInWithPopup`](!firebase_auth.FirebaseAuth.signInWithPopup) method. This will trigger a new
window to appear prompting the user to sign-in to your GitHub application:

```dart
Future<UserCredential> signInWithGitHub() async {
  // Create a new provider
  GithubAuthProvider githubProvider = GithubAuthProvider();

  // Once signed in, return the UserCredential
  return await FirebaseAuth.instance.signInWithPopup(githubProvider);

  // Or use signInWithRedirect
  // return await FirebaseAuth.instance.signInWithRedirect(githubProvider);
}
```

</TabItem>
</Tabs>
